package com.adee.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {
    public static void main(String[] args) throws Exception{
        // 启动服务器等待用户请求，然后用线程池处理每个请求
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        while (true) {
            System.out.println("等待客户端请求...");
            Socket socket = serverSocket.accept();
            executorService.execute(() -> {
                handler(socket);
            });
        }
    }

    // 处理请求
    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        try {
            System.out.println("新的客户端请求已建立");
            InputStream inputStream = socket.getInputStream();
            int len;
            while (true) {
                System.out.println("阻塞读取客户端数据");
                len = inputStream.read(bytes);
                if(len == -1) break;
                System.out.print(new String(bytes, 0, len));
            }
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭客户端连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
